/*
 Copyright (C) 2009 QDSS.org
 
 This program is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation, either version 3 of the License, or
 any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.
 
 You should have received a copy of the GNU General Public License
 along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package org.qdss.persist.exception;

import java.sql.SQLException;

import org.qdss.persist.DataAccessException;


/**
 * 
 * 
 * @author <a href="mailto:zhaofang123@gmail.com">FANGFANG ZHAO</a>
 * @since 0.1.0, Feb 11, 2009
 * @version $Id: JDBCException.java 44 2009-04-17 07:25:34Z zhaofang123@gmail.com $
 */
public class JDBCException extends DataAccessException {
	private static final long serialVersionUID = -6444431350667265965L;

	private SQLException sqlex;
	private String sql;

	public JDBCException(String message, Throwable ex) {
		super(message, ex);
	}

	public JDBCException(String message, SQLException root) {
		super(message, root);
		sqlex = root;
	}

	public JDBCException(String message, SQLException root, String sql) {
		super(message, root);
		this.sqlex = root; 
		this.sql = sql;
	}

	/**
	 * Get the SQLState of the underlying <tt>SQLException</tt>.
	 * 
	 * @see java.sql.SQLException
	 * @return String
	 */
	public String getSQLState() {
		return sqlex.getSQLState();
	}

	/**
	 * Get the <tt>errorCode</tt> of the underlying <tt>SQLException</tt>.
	 * 
	 * @see java.sql.SQLException
	 * @return int the error code
	 */
	public int getErrorCode() {
		return sqlex.getErrorCode();
	}

	/**
	 * Get the underlying <tt>SQLException</tt>.
	 * 
	 * @return SQLException
	 */
	public SQLException getSQLException() {
		return sqlex;
	}

	/**
	 * Get the actual SQL statement that caused the exception (may be null)
	 */
	public String getSQL() {
		return sql;
	}

	@Override
	public String toString() {
		StringBuilder sb = new StringBuilder();
		sb.append("-- SQL Error ------------------------------------------------------------------------");
		sb.append("\nCategory:    ").append(getClass());
		sb.append("\nSQL:         ").append(sql);
		sb.append("\nVendorError: ").append(getErrorCode());
		sb.append("\nSQLState:    ").append(getSQLException().getSQLState());
		sb.append("\nCause:       ").append(sqlex);
		sb.append("\nMessage:     ").append(getMessage());
		
		return sb.toString();
	}
}
